use std::path::Path;
use anyhow::Result;
use ark_bn254::{Bn254, Fr};
use ark_groth16::{
    Proof, VerifyingKey, 
    prepare_verifying_key, 
    verify_proof as ark_verify_proof
};
use ark_serialize::CanonicalDeserialize;
//use ark_groth16::{generate_random_parameters, create_random_proof, Proof, ProvingKey, Parameters};
use ark_serialize::CanonicalSerialize;
use rand::thread_rng;
use chrono::Utc;
use chrono::Datelike;
use crate::circuit::age_range::AgeRangeCircuit;
use ark_bn254::Parameters;
pub struct AgeRangeChecker {
    vk: VerifyingKey<Bn254>,
    pvk: ark_groth16::PreparedVerifyingKey<Bn254>,
}

impl AgeRangeChecker {
    pub fn new(circuit_path: &Path) -> Result<Self> {
        // 1. 加载参数
        //let params = VerifyingKey::<Bn254>::deserialize(circuit_path)?;
        
        // 2. 获取验证密钥 新版直接加载
        //let vk = params.vk;

        let vk = VerifyingKey::<Bn254>::deserialize(
            &mut std::fs::File::open(circuit_path)?
        )?;
        // 3. 准备验证密钥
        let pvk = prepare_verifying_key(&vk);
        
        Ok(Self { vk, pvk })
    }
    
    pub fn verify_proof(
        &self,
        proof: &Proof<Bn254>,
        birth_year: u32,
        min_age: u32,
        max_age: u32,
        current_year: u32,
    ) -> Result<bool> {
        let public_inputs = vec![
            Fr::from(birth_year as u64),
            Fr::from(min_age as u64),
            Fr::from(max_age as u64),
            Fr::from(current_year as u64),
        ];
        
        let valid = ark_verify_proof(
            &self.pvk,
            proof,
            &public_inputs,
        )?;
        
        Ok(valid)
    }
} 